package com.hjw.httpclient.demo;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * 设置请求的连接超时时间和读取超时间
 *
 * @author hjwStrart
 * @time 2022-11-20 11:46
 * @version: 1.0
 */
public class Demo6 {

    @Test
    public void method() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
//        String urlStr = "www.baidu.com";  定义urlStr时，不携带 "http://" 会报 Target host is not specified异常
        String urlStr = "http://www.baidu.com";
        URIBuilder builder = new URIBuilder(urlStr);
        HttpGet httpGet = new HttpGet(builder.build().toString());
        // 对每一个请求进行配置，会覆盖全局的默认请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   // 单位毫秒，连接超时时间（允许连接urlStr的最大时间，完成TCP三次握手的时间上线）
                .setSocketTimeout(3000)    // 单位毫秒，读取超时时间（表示从网址获取响应数据的时间间隔，可能响应数据分为多次）
                .setConnectionRequestTimeout(5000)  // 从连接池中获取 connection 的超时时间
                .build();
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        try {
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                System.out.println("请求成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
